<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="书籍名称" prop="bookName">
          <el-input v-model="dataForm.bookName" placeholder="书籍名称"></el-input>
        </el-form-item>
        <el-form-item label="书籍作者" prop="author">
          <el-input v-model="dataForm.author" placeholder="书籍作者"></el-input>
        </el-form-item>
        <el-form-item label="讲师" prop="speaker">
          <el-input v-model="dataForm.speaker" placeholder="讲师"></el-input>
        </el-form-item>
        <el-form-item label="书籍章节数" prop="chapterNumber">
          <el-input v-model="dataForm.chapterNumber" placeholder="书籍章节数"></el-input>
        </el-form-item>
        <el-form-item label="书籍封面" prop="coverUrl">
          <!-- <el-button type="primary" @click="uploadHandle()">上传文件</el-button> -->
          <img :src="dataForm.coverUrl" v-if="dataForm.id" style="width: 40px;height: 40px;">
          <img
            :src="dataForm.coverUrl"
            v-if="!dataForm.id"
            style="width: 40px;
          height: 40px;"
          >
          <el-upload
            class="upload-demo"
            :action="url"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="图书字数" prop="wordNumber">
          <el-input v-model="dataForm.wordNumber" placeholder="图书字数"></el-input>
        </el-form-item>
        <el-form-item label="推荐文案" prop="briefIntroduction">
          <el-input v-model="dataForm.briefIntroduction" placeholder="推荐文案"></el-input>
        </el-form-item>
        <el-form-item label="书籍简介" class="content" prop="bookDesc">
          <template>
            <script :id="ueId" class="ueditor-box" type="text/plain">{{dataForm.bookDesc}}</script>
          </template>
        </el-form-item>
         <el-form-item label="有无视频" prop="hasVideo" v-if="!dataForm.id">
           <el-radio  label="1" v-model="dataForm.hasVideo" border>有</el-radio>
           <el-radio  label="0" v-model="dataForm.hasVideo" border>无</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview()">预览</el-button>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog  :close-on-click-modal="false"
      :visible.sync="qrcode"  width="30%">
      <div class="qrcode">
        <img :src="qrimg"/>
      </div>
    </el-dialog>
  </div>
</template>
<style >
.el-upload-dragger {
  border: none;
  width: 0px;
}
.upload {
  display: inline-block;
  width: 100px;
  height: 30px;
  background-color: #409eff;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.qrcode{
    width: 200px;
    height: 200px;
    margin: 0 auto;
}
.qrcode img{
  width: 100%;
  height: 100%;
}
.ueditor-box {
  /*height: 150px;*/
  /* width: 60%; */
   width: 100% !important;
   height: 300px !important;
}
/* .el-dialog{
  width: 60% !important;
} */
.content {
  height: 600px !important;
}
/* .edui-notadd{
    width: 800px !important;
    z-index: 3000;
    height: 585px !important;
} */
</style>
<script>
import ueditor from "ueditor";
export default {
  data() {
    return {
      visible: false,
      qrcode:false,
      contentview: false,
      dataForm: {
        id: 0,
        bookName: "",
        briefIntroduction: "",
        bookDesc: "",
        author: "",
        speaker: "",
        coverUrl: "", //头像
        chapterNumber: "",
        wordNumber: "",
        bookToken: "",
        bookVisit: "",
        bookHeat: "",
        gmtCreated: "",
        gmtUpdate: "",
        bookDesc: "",
        hasVideo:'',
      },
      dataRule: {
        bookName: [
          { required: true, message: "书籍名称不能为空", trigger: "blur" },
          { max: 14, message: "最长14个字符", trigger: "blur" }
        ],
        // bookDesc: [
        //   { required: true, message: "书籍简介不能为空", trigger: "blur" }
        // ],
        author: [
          { required: true, message: "书籍作者不能为空", trigger: "blur" },
          { max: 20, message: "最长20个字符", trigger: "blur" }
        ],
        speaker: [
          { required: true, message: "主讲人不能为空", trigger: "blur" },
          { max: 20, message: "最长20个字符", trigger: "blur" }
        ],
        briefIntroduction: [
          { required: true, message: "推荐文案不能为空", trigger: "blur" }
        ],
        chapterNumber: [
          { required: true, message: "书籍章节数不能为空", trigger: "blur" }
        ]
      },
      fileList: [],
      url: "",
      ue: null,
      ueId: `J_ueditorBox_${new Date().getTime()}`,
      ueContent: "",
      qrimg:'',//二维码
      getQr:'',
    };
  },
  mounted() {
    this.url = this.$http.adornUrl(
      `/course/bookinfo/upload?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
    init(id) {
      setTimeout(() => {
      this.ue = ueditor.getEditor(this.ueId, {
        // serverUrl: '', // 服务器统一请求接口路径
        zIndex: 3000
      });
    }, 100);
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/course/bookinfo/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.bookName = data.bookInfo.bookName;
              this.dataForm.speaker = data.bookInfo.speaker;
              this.dataForm.author = data.bookInfo.author;
              this.dataForm.coverUrl = data.bookInfo.coverUrl;
              this.dataForm.chapterNumber = data.bookInfo.chapterNumber;
              this.dataForm.wordNumber = data.bookInfo.wordNumber;
              this.dataForm.briefIntroduction = data.bookInfo.briefIntroduction;
              this.dataForm.bookDesc = data.bookInfo.bookDesc;
              this.dataForm.hasVideo = data.bookInfo.hasVideo+'';
              this.ue.ready(() => {
                this.ue.setContent(this.dataForm.bookDesc);
              });
            }
          });
        }
      });
    },
    // 预览书籍简介
    preview() {
      this.ue.ready(() => {
        this.ueContent = this.ue.getContent();
      });
     this.getQr = this.ueContent.replace(/<img/g, "<img style='width:100%;height:auto'");

          this.$http({
            url: this.$http.adornUrl('/course/bookinfo/getQr'),
            method: "post",
            data: this.$http.adornData({
              bookDesc: this.getQr
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
                this.qrcode=true;
                this.qrimg=data.qrUrl
                // console.log(data)
            } else {
              this.$message.error(data.msg);
            }
          });
    },
    //上传封面
    handleAvatarSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm("操作成功, 是否继续操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).catch(() => {
            this.visible = false;
          });
        }
        this.dataForm.coverUrl = response.url;
      } else {
        this.$message.error(response.msg);
      }
    },
    //ok
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传封面只能是 png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面大小不能超过 2MB!");
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 408;
        let height = 540;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传的封面必须是408*540!");
          return Promise.reject();
        }
      );
      return isJPG && isLt2M && isSize;
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 表单提交
    getContent(res, file) {
      this.ue.ready(() => {
        this.ueContent = this.ue.getContent();
      });
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/course/bookinfo/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              bookName: this.dataForm.bookName,
              briefIntroduction: this.dataForm.briefIntroduction,
              author: this.dataForm.author,
              speaker: this.dataForm.speaker,
              coverUrl: this.dataForm.coverUrl,
              chapterNumber: this.dataForm.chapterNumber,
              wordNumber: this.dataForm.wordNumber,
              bookDesc: this.ueContent,
              hasVideo:this.dataForm.hasVideo,
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
